/**
 * Copyright (c) 2011 ~ 2014 Deepin, Inc.
 *               2013 ~ 2014 jouyouyun
 *
 * Author:      jouyouyun <jouyouwen717@gmail.com>
 * Maintainer:  jouyouyun <jouyouwen717@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 **/

package main

import (
	"fmt"
	"reflect"
)

type testA struct {
	id   int32
	name string
}

type testB struct {
	key   testA
	value string
}

func printType(e interface{}) {
	t := reflect.TypeOf(e)
	fmt.Println(t.Name())
}

func isElementEqual(e1, e2 interface{}) bool {
	t1 := reflect.TypeOf(e1)
	t2 := reflect.TypeOf(e2)
	if t1 != t2 {
		return false
	}
	return reflect.DeepEqual(e1, e2)
}

func isElementInList(e interface{}, list interface{}) bool {
	v := reflect.ValueOf(list)
	fmt.Printf("%v\n", v.Kind())
	if v.Type().Kind() != reflect.Slice &&
		v.Type().Kind() != reflect.Array {
		fmt.Printf("Not Array\n")
		return false
	}

	l := v.Len()
	for i := 0; i < l; i++ {
		fmt.Printf("%d: %v\n", i, v.Index(i))
		if reflect.DeepEqual(e, v.Index(i).Interface()) {
			fmt.Printf("True\n")
			return true
		}
	}

	return false
}

func test1() {
	a := testA{1, "a"}
	a2 := testA{2, "a"}
	b := testB{a, "test"}
	c := testB{a, "test"}
	d := &testB{a, "test"}
	array := []testB{b, c}

	printType(a)
	printType(b)
	printType(d)
	printType(array)

	fmt.Printf("%v\n", isElementEqual(&a, &a2))
	fmt.Printf("%v\n", isElementEqual(a, b))
	fmt.Printf("%v\n", isElementEqual(&c, &b))
	fmt.Printf("%v\n", isElementEqual(c, d))
	fmt.Printf("%v\n", isElementInList(a, array))
	fmt.Printf("%v\n", isElementInList(b, array))
}

func parseStruct(e interface{}) {
	if e == nil {
		return
	}

	if reflect.TypeOf(e).Kind() != reflect.Struct {
		fmt.Println("Not Struct")
		return
	}

	v := reflect.ValueOf(e)
	l := v.NumField()
	fmt.Println("Field Number:", l)
	for i := 0; i < l; i++ {
		fmt.Printf("Number: %v, Field: %v\n", i, v.Field(i))
	}
}

func main() {
	a := testA{1, "a"}
	b := testB{a, "test"}

	parseStruct(a)
	parseStruct(b)
}
